#include "farmmanagementwidget.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QFrame>
#include <QIcon>
#include <QDebug>

FarmCard::FarmCard(int farmId, const QString &description,
                   const QString &videoAddress, int status,
                   QWidget *parent)
    : QFrame(parent), farmId(farmId)
{
    // 设置卡片样式
    setStyleSheet("FarmCard {"
                 "  background-color: #f5fbf5;"
                 "  border: 1px solid #c8e6c9;"
                 "  border-radius: 8px;"
                 "  padding: 15px;"
                 "}"
                 "FarmCard:hover {"
                 "  border: 2px solid #4b8a29;"
                 "  background-color: #e8f5e9;"
                 "}");

    setFixedSize(220, 150);
    setCursor(Qt::PointingHandCursor);

    QVBoxLayout *layout = new QVBoxLayout(this);

    // 农场ID
    idLabel = new QLabel(QString("农场ID: %1").arg(farmId), this);
    idLabel->setStyleSheet("font-weight: bold; color: #2c6e49;");
    layout->addWidget(idLabel);

    // 农场描述
    descLabel = new QLabel(description, this);
    descLabel->setWordWrap(true);
    descLabel->setStyleSheet("color: #444; margin-top: 10px;");
    layout->addWidget(descLabel);

    // 状态指示器
    statusLabel = new QLabel(this);
    statusLabel->setAlignment(Qt::AlignRight);
    if (status == 1) {
        statusLabel->setText("● 在线");
        statusLabel->setStyleSheet("color: #4CAF50; font-weight: bold;");
    } else {
        statusLabel->setText("● 离线");
        statusLabel->setStyleSheet("color: #F44336; font-weight: bold;");
    }
    layout->addWidget(statusLabel);
}

void FarmCard::setSelected(bool selected)
{
    if (selected) {
        setStyleSheet("FarmCard {"
                     "  background-color: #e8f5e9;"
                     "  border: 2px solid #4b8a29;"
                     "  border-radius: 8px;"
                     "  padding: 15px;"
                     "}");
    } else {
        setStyleSheet("FarmCard {"
                     "  background-color: #f5fbf5;"
                     "  border: 1px solid #c8e6c9;"
                     "  border-radius: 8px;"
                     "  padding: 15px;"
                     "}"
                     "FarmCard:hover {"
                     "  border: 2px solid #4b8a29;"
                     "  background-color: #e8f5e9;"
                     "}");
    }
}
void FarmCard::mousePressEvent(QMouseEvent *event)
{
    Q_UNUSED(event);
    emit clicked(farmId);
}

// ===================== FarmManagementWidget 实现 =====================

FarmManagementWidget::FarmManagementWidget(QWidget *parent)
    : QWidget(parent)
{
    setupUI();
    loadFarmData();
}
void FarmManagementWidget::setupUI()
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(20, 20, 20, 20);
    mainLayout->setSpacing(15);

    // 标题
    titleLabel = new QLabel("农场管理", this);
    titleLabel->setStyleSheet("font-size: 24px; font-weight: bold; color: #2c6e49;");
    mainLayout->addWidget(titleLabel);

    // 搜索和过滤区域
    QHBoxLayout *filterLayout = new QHBoxLayout();

    searchEdit = new QLineEdit(this);
    searchEdit->setPlaceholderText("搜索农场...");
    searchEdit->setStyleSheet("QLineEdit {"
                             "  height: 35px;"
                             "  padding: 5px 10px;"
                             "  border: 1px solid #c8e6c9;"
                             "  border-radius: 4px;"
                             "}");
    connect(searchEdit, &QLineEdit::textChanged, this, &FarmManagementWidget::onSearchTextChanged);

    statusFilter = new QComboBox(this);
    statusFilter->addItem("所有状态", -1);
    statusFilter->addItem("在线", 1);
    statusFilter->addItem("离线", 0);
    statusFilter->setStyleSheet("QComboBox {"
                               "  height: 35px;"
                               "  padding: 5px 10px;"
                               "  border: 1px solid #c8e6c9;"
                               "  border-radius: 4px;"
                               "}");
    connect(statusFilter, QOverload<int>::of(&QComboBox::currentIndexChanged),
                this, &FarmManagementWidget::onStatusFilterChanged);


    filterLayout->addWidget(searchEdit);
    filterLayout->addWidget(statusFilter);
    filterLayout->setStretch(0, 3);
    filterLayout->setStretch(1, 1);


    mainLayout->addLayout(filterLayout);

    // 农场卡片区域
    scrollArea = new QScrollArea(this);
    scrollArea->setWidgetResizable(true);
    scrollArea->setStyleSheet("QScrollArea { border: none; }");

    cardsContainer = new QWidget(scrollArea);
    cardsLayout = new QGridLayout(cardsContainer);
    cardsLayout->setSpacing(20);
    cardsLayout->setContentsMargins(10, 10, 10, 10);
    cardsLayout->setAlignment(Qt::AlignTop);

    scrollArea->setWidget(cardsContainer);
    mainLayout->addWidget(scrollArea);

    // 状态栏
//    QLabel *statusBar = new QLabel("双击农场卡片查看更多详情", this);
//    statusBar->setStyleSheet("color: #757575; font-size: 12px; padding: 5px;");
//    mainLayout->addWidget(statusBar);
}

void FarmManagementWidget::loadFarmData()
{
    // 创建数据库模型
    farmModel = new QSqlTableModel(this);
    farmModel->setTable("farm_info");
    farmModel->select();

    // 检查错误
    if (farmModel->lastError().isValid()) {
        QMessageBox::critical(this, "数据库错误",
                             "无法加载农场数据:\n" + farmModel->lastError().text());
        return;
    }

    refreshFarmList();
}

void FarmManagementWidget::refreshFarmList()
{
    clearFarmCards();
    createFarmCards();
}

void FarmManagementWidget::clearFarmCards()
{
    for (FarmCard *card : farmCards) {
        cardsLayout->removeWidget(card);
        delete card;
    }
    farmCards.clear();
}

void FarmManagementWidget::createFarmCards()
{
    int row = 0;
    int col = 0;
    const int cols = 3; // 每行显示3个卡片

    for (int i = 0; i < farmModel->rowCount(); ++i) {
        int farmId = farmModel->data(farmModel->index(i, 0)).toInt();
        QString description = farmModel->data(farmModel->index(i, 1)).toString();
        QString videoAddress = farmModel->data(farmModel->index(i, 2)).toString();
        int status = farmModel->data(farmModel->index(i, 3)).toInt();

        // 应用搜索过滤
        QString searchText = searchEdit->text().toLower();
        if (!searchText.isEmpty() &&
            !description.toLower().contains(searchText) &&
            !QString::number(farmId).contains(searchText)) {
            continue;
        }

        // 应用状态过滤
        int filterStatus = statusFilter->currentData().toInt();
        if (filterStatus != -1 && status != filterStatus) {
            continue;
        }

        // 创建卡片
        FarmCard *card = new FarmCard(farmId, description, videoAddress, status, cardsContainer);
        connect(card, &FarmCard::clicked, this, &FarmManagementWidget::onFarmCardClicked);

        // 添加到布局
        cardsLayout->addWidget(card, row, col);
        farmCards.append(card);

        // 更新位置
        col = (col + 1) % cols;
        if (col == 0) row++;
    }
}

void FarmManagementWidget::onSearchTextChanged(const QString &text)
{
    Q_UNUSED(text);
    refreshFarmList();
}

void FarmManagementWidget::onFarmCardClicked(int farmId)
{
    // 更新选中状态
    selectedFarmId = farmId;

    // 更新卡片样式
    for (FarmCard *card : farmCards) {
        card->setSelected(card->getFarmId() == farmId);
    }

    // 发出选择信号
   // qDebug()<<"man:"<<farmId;
    emit farmSelected(farmId);
}



void FarmManagementWidget::onStatusFilterChanged()
{
    refreshFarmList();
}

